<template>
	<view class="p-12 ">
		<view class="bg-white p-12 round-8 flex flex-y-center flex-x-space-between">
			<image :src="form.avatar" class="round-circle w-50 h-50"></image>
			<!-- #ifdef MP-WEIXIN -->
			<button class="btn-normal  flex  flex-y-center" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<view class="text-999 fs-14">
					更换头像
					<text class="iconfont icon-youjiantou"></text>
				</view>
			</button>
			<!-- #endif -->

			<!-- #ifdef H5 -->
			<view class="text-999 fs-14" @click="selectImg">
				更换头像
				<text class="iconfont icon-youjiantou"></text>
			</view>
			<!-- #endif -->
		</view>
		<view class="bg-white round-8 p-12 mt-10 flex flex-y-center flex-x-space-between">
			<text>昵称</text>
			<input placeholder="请输入昵称" class="text-right" v-model="form.nickname" type="nickname" @change='change' />
		</view>
		<y-footer mode @success="submit">保存信息</y-footer>
	</view>
</template>

<script setup>
	import { useRefs, useUserStore, useWebConfigStore } from '@/stores'
	import { editUser } from '@/api/user.js'
	import { uploadImg } from '@/api/system.js'
	import { reactive, ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app'
	import { $tool } from '@/utils';
	const { USERINFO } = useRefs(useUserStore())
	const { getUserInfo } = useUserStore()
	const { WEBCONFIG } = useRefs(useWebConfigStore())
	const form = reactive({
		nickname: '',
		avatar: ''
	})
	const avatarStatus = ref(false)
	onLoad(() => {
		setTimeout(()=>{
		form.nickname = USERINFO.value.nickname
		form.avatar = USERINFO.value.avatar ? USERINFO.value.avatar : WEBCONFIG.value.avatar
		},300)
	})
	const submit = () => {
		if (avatarStatus.value == true) {
			uploadImg({ filePath: form.avatar, name: 'file', is_hide: 1}).then(res => {
				form.avatar=res.data.file_url
				edit()
			})
		} else {
			form.avatar = '';
			edit()
		}
	}
	const edit = () => {
		editUser(form).then(res => {
		avatarStatus.value = false
			$tool.toast('修改成功')
			getUserInfo()
		})
	}
	const change = (e) => {
		form.nickname = e.detail.value
	}

	const onChooseAvatar = (e) => {
		avatarStatus.value = true
		form.avatar = e.detail.avatarUrl
	}

	const selectImg = () => {
		uni.chooseImage({
			count: 1,
			success(res) {
				avatarStatus.value = true
				form.avatar = res.tempFilePaths[0]
			}
		})
	}
</script>

<style>

</style>